<?php

namespace App\Http\Controllers;

use App\Models\TranslateSubscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Auth;
use Flash;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use App\Models\Topic;
use App\Models\TranslateSection;
use App\Models\TranslateRecord;
use App\Models\TranslateImprovedRecord;
use Mockery\Exception;
use Symfony\Component\Translation\Catalogue\TargetOperation;
use App\Http\Requests\UserTranslateRequest;
use App\Activities\UserSubscribedTranslate;

class UserTranslateController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * 翻译文章详情数据
     * @param $id
     *
     */
    public function getTranslateInfo($id)
    {
        $topic = Topic::with(['translateSections'=>function($query){
                $query->orderBy('updated_at','desc');
            }])
            ->with(['translateSections.TranslateRecord'=>function($query){
                $query->where(['status'=>2])->with('Translator');
            }])
            ->where('id',$id)->firstOrFail();

        //文章创建时间格式化
        $created_at='';
        if(sizeof($topic->translateSections)){
            $created_at=Carbon::parse($topic->translateSections[0]->created_at)->diffForHumans();
        }
        //文章更新时间
        $updated_at='';
        if(sizeof($topic->translateSections) && $topic->translateSections[0]->updated_at){
            $updated_at=Carbon::parse($topic->translateSections[0]->updated_at)->diffForHumans();
        }
        //dd($topic);
    }

    /**
     * 去添加翻译页面
     * @param Request $request
     * @return bool
     *
     */
    public function create(UserTranslateRequest $request)
    {
        $params = $request->all();

        $user = Auth::user();

        $section = TranslateSection::where('id',$params['section_id'])->firstOrFail();

        $topic = Topic::where('id', $section->topic_id)->firstOrFail();

        $type = $params['type'];

        $data = compact('section', 'topic', 'type');

        if($type == 1) //首译,有可能有多个用户
        {
            $time_long = $params['time_long'];

            $data = compact('section', 'topic', 'type', 'time_long');

            $section->setLockedDateAttribute(Carbon::now()->addMinutes($params['time_long']));

        }
        elseif($type == 3) //改进
        {
            $record = TranslateRecord::where('id', $params['record_id'])->firstOrFail();

            $data = compact('section', 'topic', 'type', 'record');

        }


        return view('translate.translate_create_edit', $data);

    }

    /**
     * @param $section
     * @param $params
     * @param $type
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    private function createRecord($params,$type)
    {
        $record = new TranslateRecord();
        try
        {
            //DB::beginTransaction();

            //dd($params['translate_text']);
            $new_record = [
                'translate_section_id' => $params['section_id'],
                'status' => TranslateRecord::STATUS_NOT_AUDIT,
                'type' => $type,
                'translate_text' => $params['translate_text'],
                'translate_time' => $params['translate_start_time'],
                'translator_id' => Auth::user()->id
            ];

            $record = TranslateRecord::create($new_record);

            //DB::commit();
        }
        catch (Exception $exception)
        {
            //DB::rollBack();
            //return response($exception->getMessage(),500);
        }

        return $record;
    }
    /**
     * 保存翻译
     * @param Request $request
     * @return bool|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     *
     */
    public function save(UserTranslateRequest $request)
    {
        $params = $request->all();

        $type = $params['type'];

        $topic_id = $params['topic_id'];

        $topic = Topic::where('id', $topic_id)->firstOrFail();
        $user_ids_arr = $topic->translatorIds();

        if($type == 1 || $type == 2)
        {
            $trans_record = $this->createRecord($params,$type);

            //$translator_ids = $trans_record->translateSection->getAttrbute('translator_ids');

            if(!in_array(Auth::user()->id, $user_ids_arr))
            {
                $trans_record->translateSection->increment('translator_count');
            }

        }
        elseif($type == 3)
        {
            //创建改进的译文
            $trans_improved_record = new TranslateImprovedRecord();
            $data = ['translate_record_id' => $params['record_id'],
                    'translate_text' => $params['translate_text'],
                    'translator_id' => Auth::user()->id];

            $trans_improved_record = $trans_improved_record->create($data);
            //这里不管审核状态，直接加上翻译人员
            //$translator_ids = $trans_improved_record->translateRecord->translateSection->getAttrbute('translator_ids');
            if(!in_array(Auth::user()->id, $user_ids_arr))
            {
                $trans_improved_record->translateRecord->translateSection->increment('translator_count');
            }

            //$improved_user_ids = $trans_improved_record->translateRecord->getAttrbute('improved_user_ids');

            $improved_user_ids_arr = $topic->improvedUserIds();

            if(!in_array(Auth::user()->id, $improved_user_ids_arr))
            {
                $trans_improved_record->translateRecord->increment('improved_user_num');
            }

        }

        //这里section的lock_date不更改，存储的是最后一个首译的锁定时间

        return redirect()->route('topics.show',['id' => $topic_id]);

    }


    public function edit($record_id)
    {
        $record = TranslateRecord::where('id', $record_id)->get();

        $section = $record->translateSection();

        $topic = $section->topic();

        $data = compact('section', 'topic', 'type', 'time_long', 'record');
        return view('translate.translate_create_edit', $data);
    }
    /**
     * @param UserTranslateRequest $request
     */
    public function update(UserTranslateRequest $request)
    {

    }

    public function vote($record_id)
    {
        $record = TranslateRecord::findOrFail($record_id);
        $type = app('Phphub\Vote\Voter')->transRecordUpVote($record);

        return response([
            'status'  => 200,
            'message' => lang('Operation succeeded.'),
            'type'    => $type['action_type'],
        ]);
    }

    public function subscribe()
    {
        $subscriber = TranslateSubscriber::withTrashed()->where(['user_id' => Auth::user()->id])->get();
        if(count($subscriber))
        {
            $subscriber = TranslateSubscriber::withTrashed()->where(['user_id' => Auth::user()->id])->firstOrFail();
            $subscriber->restore();
        }
        else
        {
            TranslateSubscriber::create(['user_id' => Auth::user()->id]);
        }

        Flash::success("订阅成功");
        app(UserSubscribedTranslate::class)->generate(Auth::user());
        return redirect()->back();
    }

    public function unSubscribe()
    {
        TranslateSubscriber::where(['user_id' => Auth::user()->id])->delete();
        Flash::success("成功取消订阅");
        app(UserSubscribedTranslate::class)->remove(Auth::user());
        return redirect()->back();
    }
}
